<template>
	<view class="Contain"> <!-- Contain Start -->
		 <view class="MyFamily">
			<view class="info">
				<u-row gutter="0">
					<u-col span="3" text-align="left">
						<view class="left">收件人</view>
					</u-col>
					<u-col span="9" text-align="left">
						<view class="blod right"><u-input v-model="username" type="text" placeholder="请输入收件人" :border="false" height="48"/></view>
					</u-col>
				</u-row> 	 
			</view>
			<view class="info">
				<u-row gutter="0">
					<u-col span="3" text-align="left">
						<view class="left">手机号码</view>
					</u-col>
					<u-col span="9" text-align="left">
						<view class="blod right"><u-input v-model="tel" type="number" placeholder="请输入手机号码" :border="false" height="48"/></view>
					</u-col>
				</u-row> 	
			</view>
			<view class="info">
				<u-row gutter="0">
					<u-col span="3" textAlign="left">
						<view class="left">省/城/区</view>
					</u-col>
					<u-col span="7" textAlign="left">
						<view class="blod right" style="position:relative;top:0px;" @click="handleGetRegion">
							<block v-if="finalCityVal===''">
								<u-input v-model="finalCityVal" :disabled="true" disabledColor="#FFFFFF" type="text" placeholder="选择省/城/区" :border="false" height="48"/>
							</block>
							<block v-else>
								<view>{{finalCityVal}}</view>
							</block>
						</view>
					</u-col>
					<u-col span="2" textAlign="right" justify="end">
						<view class="left ricon" @click="handleGetRegion"><u-icon name="arrow-right" color="#ccc" size="22"></u-icon></view>
					</u-col>	
				</u-row> 	
			</view>
			<view class="info" style="border-bottom:0px; padding-bottom:0px;">
				<u-row gutter="0">
					<u-col span="3" text-align="left">
						<view class="left">详细地址</view>
					</u-col>
					<u-col span="7" text-align="left">
						<view class="blod right" style="position:relative;top:0px;">
							<u-input v-model="adr" type="textarea" placeholder="街道、门牌号等" :border="false" height="48"/>
						</view>
					</u-col>
					<u-col span="1" text-align="right">
						<view class="left"><u-icon name="map" color="#017bff" size="38"></u-icon></view>
					</u-col>		
				</u-row> 	
			</view>
			
			
			<!-- 间隔槽 -->	
			<u-gap height="20" bg-color="#F7F9FD" margin-top="20" margin-bottom="0"></u-gap>		 
		 
			<view class="info" style="border-bottom:0px; padding-bottom:0px;">
				<u-row gutter="0">
					<u-col span="4" text-align="left">
						<view class="left">设为默认地址</view>
					</u-col>
					<u-col span="8" text-align="right">
						<view class="blod right" style="position:relative;top:5rpx; left:10rpx;"><u-switch v-model="checked" @change="switchchange"></u-switch></view>
					</u-col>
				</u-row> 	
			</view>			
			
			<view class="oneKeyAdr">
				<u-button type="primary" :custom-style="oneKeyAdrbtncustomstyle" shape="circle" @click="oneKeyAdr">微信一键获取</u-button>
			</view>
			
			<view class="deladr" @click="deladdress" v-if="isEditor===true">
				<u-icon name="trash" color="#ccc" size="38" style="position:relative;top:5rpx;"></u-icon> 
				<text class="gray" style="margin-left:10rpx;">删除收货地址</text>
			</view>
			
		 </view> <!-- MyFamily End -->
		
		

		 <view class='NewAdd'><u-button type="primary" :custom-style="btncustomstyle" @click="submit">{{btnText}}</u-button></view>
		 	  
			  
		<!-- 城市下拉组件  @change="accepted" -->
		<fd-picker ref="fdpicker" @change="accepted"></fd-picker>	  
			  
	</view> <!-- Contain End -->
</template>

<script setup lang="ts">
	
import { ref,reactive } from 'vue'
import { GoUrl,Toast } from '@/utils/utils'
import {onShow,onLoad } from '@dcloudio/uni-app'

let region=reactive<any>([]);
let defaultRegion=reactive<any>(['广东省','广州市','番禺区']);
let defaultRegionCode=ref("440113");
let isEditor=ref(false)
let dataid=ref("")
let checked=ref(false)
let userAddress=ref(uni.getStorageSync("userAddress")?uni.getStorageSync("userAddress"):null) //读取缓存修改地址
let username=ref("") //张三
let tel=ref("") //13012345678
let regiondata=reactive<any>([]);
let showPCA=ref(false)
let pca=ref("")
let adr=ref("")
let btncustomstyle=reactive<any>({
				"width":"93%",
				"background":"#3288FD",
				"padding":"10rpx 0",
				"marginTop":"30rpx",
				"color":"#FFFFFF",
				"fontSize":"30rpx",
});
let oneKeyAdrbtncustomstyle=reactive<any>({
				"width":"38%",
				"background":"#00a100",
				"padding":"10rpx 0",
				"marginTop":"70rpx",
				"color":"#FFFFFF",
				"fontSize":"30rpx",
				"borderRedius":"100rpx",
				"border":"0rpx"
});
let btnText=ref("确定")
let cityVal=ref("")


//城市下拉组件
let finalCityVal=ref(""); //将省市区合并
let packRow=reactive([]);
const accepted=(e:any)=>{
	console.log("城市组件",e);
	packRow = e
	finalCityVal.value=e[0].lablel+" / "+e[1].lablel+" / "+e[2].lablel
	cityVal.value=e[0].lablel+" "+e[1].lablel+" "+e[2].lablel
	console.log("选择区域值:",cityVal.value);
}
const fdpicker:any=ref();
const handleGetRegion=()=>{ 
	console.log(fdpicker);
	 fdpicker.value?.showCity()  //显示下拉组件
	 fdpicker.value?.reelect()
}



let regionName=()=>{
	// 转为字符串
	return region.map(item=>item.name).join(' ')
}

onShow(()=>{
	userAddress.value=uni.getStorageSync("userAddress")?uni.getStorageSync("userAddress"):null;
	console.log("编辑地址:",userAddress.value);
	if(userAddress.value!=null){
		isEditor.value=true;
		btnText.value="更新";
		uni.setNavigationBarTitle({
			title:'编辑收货地址'
		})
		dataid.value=userAddress.value.id;
		username.value=userAddress.value.userName;
		tel.value=userAddress.value.phone;
		finalCityVal.value=userAddress.value.address.split(" ")[0]+" / "+userAddress.value.address.split(" ")[1]+" / "+userAddress.value.address.split(" ")[2]
		cityVal.value=userAddress.value.address.split(" ")[0]+" "+userAddress.value.address.split(" ")[1]+" "+userAddress.value.address.split(" ")[2]
		adr.value=userAddress.value.detailadr;
		checked.value=userAddress.value.isDefault==="默认地址"?true:false; //是否默认地址
	}	
})


const resetData=()=>{
	username.value="";
	tel.value="";
	cityVal.value="";
	finalCityVal.value="";
	adr.value="";
	checked.value=false;
}


const deleteAdress=async ()=>{
	let paraData={
		id:dataid.value,
	};
	console.log("删除收货地址",paraData);
	/* let res = await deleteAdressData(paraData);
	console.log("删除收货地址",res);
	if(res.data.code===200){
		uni.hideLoading();
		uni.removeStorageSync("userAddress");
		Toast("地址已删除");
		setTimeout(()=>{
			GoUrl("../shop_selectedAddress/shop_selectedAddress",1);
		},1000)
	}else{
		uni.hideLoading();
	} */
	uni.$tools.Reqeust('/shopApi/deleteAdress',paraData,'POST').then((res:any)=>{
		console.log("删除收货地址",res);
		if(res.data.code===200){
			isEditor.value=false;
			btnText.value="确定";
			resetData(); //复位数据
			uni.$tools.Toast("收货地址已删除");
		}else{
			uni.$tools.Toast(res.data.msg);
		}
	});	
}


const updateUserAdress=async ()=>{
	let paraData:any={
		id:dataid.value,
		adrname:username.value,
		adrphone:tel.value,
		address:cityVal.value,
		detailadr:adr.value,
		isdefault:checked.value===true?"默认地址":"",
	};
	console.log("更参数:",paraData);
	// let res = await updateAdressData(paraData);
	// console.log("更新收货地址:",res);
	// if(res.data.code===200){
	// 	uni.hideLoading();
	// 	uni.removeStorageSync("userAddress");
	// 	Toast("地址已更新");
	// 	setTimeout(()=>{
	// 		GoUrl("../shop_selectedAddress/shop_selectedAddress",1);
	// 	},1000)
	// }else{
	// 	uni.hideLoading();
	// }			
	uni.$tools.Reqeust('/shopApi/updateAdress',paraData,'POST').then((res:any)=>{
		console.log("添加收货地址",res);
		if(res.data.code===200){
			if(res.data.msg==='新增收货地址成功'){
				isEditor.value=true;
				dataid.value=res.data.addressid;
				btnText.value="更新";
				uni.$tools.Toast("地址添加成功");
			}
		}else{
			uni.$tools.Toast(res.data.msg);
		}
	});	
}


const addUserAdress=async ()=>{
	let paraData={
		token:uni.getStorageSync("token"),
		adrname:username.value,
		adrphone:tel.value,
		address:cityVal.value,
		detailadr:adr.value,
		isdefault:checked.value===true?"默认地址":"",
	};
	 console.log("添加收货地址",paraData);
	//  let res = await addUserAdressData(paraData);
	//  console.log("添加收货地址服务器返回==>",res);
	// if(res.data.code===200){
	// 	uni.hideLoading();
	// 	uni.removeStorageSync("userAddress");
	// 	GoUrl("../shop_selectedAddress/shop_selectedAddress",1);
	// }else{
	// 	uni.hideLoading();
	// }
	uni.$tools.Reqeust('/shopApi/addAdress',paraData,'POST').then((res:any)=>{
		console.log("添加收货地址",res);
		if(res.data.code===200){
			if(res.data.msg==='新增收货地址成功'){
				isEditor.value=true;
				dataid.value=res.data.addressid;
				btnText.value="更新";
				uni.$tools.Toast("地址添加成功");
			}
		}else{
			uni.$tools.Toast(res.data.msg);
		}
	});
}


const oneKeyAdr=()=>{
	uni.authorize({
		scope: 'scope.address',
		success() {
			console.log("成功");
			uni.chooseAddress({
			  success:(res)=>{
				/* console.log(res.userName)
				console.log(res.postalCode)
				console.log(res.provinceName)
				console.log(res.cityName)
				console.log(res.countyName)
				console.log(res.detailInfo)
				console.log(res.nationalCode)
				console.log(res.telNumber) */
				username.value=res.userName;
				tel.value=res.telNumber;
				cityVal.value=res.provinceName+" "+res.cityName+" "+res.countyName;
				finalCityVal.value=cityVal.value;
				adr.value=res.detailInfo;
			  },
			  fail:err=>{
				 console.log("一键获取地址失败",err); 
			  }
			})
		}
	})
}





const deladdress=()=>{
	uni.showModal({
		title: '提示',
		content: '是否删除该地址',
		success:(res)=>{
			if (res.confirm) {
				deleteAdress();
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});					
}


const switchchange=(status:boolean)=>{
	console.log("是否默认地址:",status);
	checked.value=status;
}


//省市区
const confirmData=(e:any)=>{
 	pca.value=e.province.label+" "+e.city.label+" "+e.area.label;
	console.log("选择城市结果:",e,pca);
}


const submit=()=>{
	if (/\S/.test(username.value)===false){
		Toast("请输入收件人姓名");
		return;
	}
	/* if (uni.$u.test.chinese(username)===false){
		Toast("请输入中文姓名");
		return;					
	} */
	if (/\S/.test(tel.value)===false){
		Toast("请输入手机号码");
		return;
	}
	if (/\S/.test(cityVal.value)===false){
		Toast("请选择省/市/区");
		return;
	}
	if(/\S/.test(adr.value)===false){
		Toast("请输入详细收货地址")
		return;
	}
	if(isEditor.value===true){
		updateUserAdress();
	}else{
		addUserAdress();
	}
}


//保存用户信息
const SaveAddress=()=>{
	let paraData=reactive<any>( {
		//pca字段都有空格
		//广东省 湛江市 霞山区 明和大道51号
		address:pca.value+" "+adr.value,
		isDefault:checked.value===true?1:0,
		phone:tel,
		userName:username.value
	})
	//追加更新id
	if(isEditor.value===true){
		paraData.id=userAddress.id;
	}
	/* console.log("保存用户信息参数:",paraData);
	shoputils.AddAddress(UserToken,paraData,res=>{
		if(res.code===0){		
			$Go('../shop_selectedAddress/shop_selectedAddress');
		}
	}) */
}


const confirm=()=>{
	let paraData=reactive<any>( {
		id:userAddress.id
	});
	console.log("删除地址参数:",paraData);
	/* shoputils.DelAdr(UserToken,paraData,res=>{
		if(res.code===0){
			uni.removeStorageSync("userAddress");  //清空一次地址缓存 
			Toast("地址已删除");
			setTimeout(()=>{
				$back();
			},1000)
		}
	}) */
}

const cancel=()=>{ 
	console.log("当前调用页面cancel");
}
</script>
<style>
	page{
		padding-bottom:200rpx;
	}
</style>
<style scoped lang="scss" >
	@import "shop_addAddress.scss";
</style>